import { useMemo } from 'react'
import dayjs from 'dayjs'
import { Tag } from 'antd'
import { StatusPanelDef } from '@ag-grid-community/core'

import { CusAgGrid, ICusAgGridProps } from '@/components/CusAgGrid'
import { UnifiedPagination } from '@/components/UnifiedPagination'
import { addAGCellTexty } from '@oBiz/components/addTexty'
import { Filter } from './Filter'
import { AllPublishPathODTO, TCellParams, TCol } from './interface'
import { useBoundStore } from './store'
import { useEventList } from './useEventList'
import { getLocationTypeName, getShipTrackStatusName, getVisibleFlagName } from './utils'
import style from './styles.module.less'

const Cell = (p: TCellParams) => {
  const { field } = p.colDef || {}
  switch (field) {
    case 'shipTrackStatus': {
      const status = getShipTrackStatusName(p.value as number)
      return status ? (
        <Tag color={getShipTrackStatusName.colorMap[p.value as number as keyof typeof getShipTrackStatusName.colorMap]}>
          {status}
        </Tag>
      ) : (
        ''
      )
    }
    case 'locationType': {
      return getLocationTypeName(p.value as number)
    }
    case 'visibleFlag': {
      return <Tag color={p.value ? 'success' : 'error'}>{getVisibleFlagName(p.value as number)}</Tag>
    }
    default: {
      return addAGCellTexty(p)
    }
  }
}

export const EventList = () => {
  useEventList()

  const gridRef = useBoundStore(v => v.gridRef)
  const loading = useBoundStore(v => v.request?.loading)
  const data = useBoundStore(v => v.request?.data)
  const page = useBoundStore(v => v.reqData.page)
  const size = useBoundStore(v => v.reqData.size)

  const setReqData = useBoundStore(v => v.setReqData)
  const getData = useBoundStore(v => v.getData)

  // 勾选统计 & 分页器
  const statusBar = useMemo<ICusAgGridProps['statusBar']>(() => {
    const statusPanels: StatusPanelDef[] = []
    statusPanels.push({
      statusPanel: UnifiedPagination,
      statusPanelParams: UnifiedPagination.defineProps({
        current: page,
        pageSize: size,
        total: data?.total,
        onChange: (page, size) => {
          setReqData({ page, size })
          getData(true)
        },
      }),
    })
    return { statusPanels }
  }, [data?.total, getData, page, size, setReqData])

  const columnDefs = useMemo<ICusAgGridProps['columnDefs']>(
    () => [
      {
        headerName: '运单号',
        field: 'waybillNo',
        minWidth: 160,
      } satisfies TCol<'waybillNo'>,
      {
        headerName: 'FBA ID',
        field: 'fbaId',
        minWidth: 130,
      } satisfies TCol<'fbaId'>,
      {
        headerName: '客户可见',
        field: 'visibleFlag',
        minWidth: 130,
        valueFormatter: ({ value }) => getVisibleFlagName(value) || '',
      } satisfies TCol<'visibleFlag'>,
      {
        headerName: '中文路由',
        field: 'templateCn',
        minWidth: 130,
      } satisfies TCol<'templateCn'>,
      {
        headerName: '英文路由',
        field: 'templateEn',
        minWidth: 130,
      } satisfies TCol<'templateEn'>,
      {
        headerName: '发生时间',
        field: 'eventTime',
        minWidth: 180,
        valueFormatter: ({ value: v }) => (v ? dayjs(v).$formatSmart($F_YMDHms) : ''),
      } satisfies TCol<'eventTime'>,
      {
        headerName: 'EDD',
        field: 'currentEdd',
        minWidth: 180,
        valueFormatter: ({ value: v }) => (v ? dayjs(v).$formatSmart($F_YMD) : ''),
      } satisfies TCol<'currentEdd'>,
      {
        headerName: 'Location类型',
        field: 'locationType',
        minWidth: 160,
        valueFormatter: ({ value }) => getLocationTypeName(value) || '',
      } satisfies TCol<'locationType'>,
      {
        headerName: 'Location',
        field: 'location',
        minWidth: 130,
      } satisfies TCol<'location'>,
      {
        headerName: '客户',
        field: 'customer',
        width: 130,
      } satisfies TCol<'customer'>,
      {
        headerName: '备注',
        field: 'note',
        width: 130,
      } satisfies TCol<'note'>,
      {
        headerName: '同步ShipTrack',
        field: 'shipTrackStatus',
        minWidth: 160,
        valueFormatter: ({ value }) => getShipTrackStatusName(value) || '',
      } satisfies TCol<'shipTrackStatus'>,
      {
        headerName: 'Status Code',
        field: 'statusCode',
        minWidth: 160,
      } satisfies TCol<'statusCode'>,
      {
        headerName: 'Reason Code',
        field: 'reasonCode',
        minWidth: 160,
      } satisfies TCol<'reasonCode'>,
      {
        headerName: '发布人',
        field: 'createBy',
        minWidth: 130,
      } satisfies TCol<'createBy'>,
      {
        headerName: '发布时间',
        field: 'createAt',
        minWidth: 180,
        sortable: true,
        valueFormatter: ({ value: v }) => (v ? dayjs(v).$formatSmart($F_YMDHms) : ''),
      } satisfies TCol<'createAt'>,
    ],
    [],
  )

  // 列配置
  const defaultColDef = useMemo<Partial<TCol>>(
    () => ({
      flex: 1,
      minWidth: 130,
      sortable: false,
      cellRenderer: Cell,
    }),
    [],
  )

  return (
    <div className={style.box}>
      <div className={style.filter}>
        <Filter />
      </div>
      <div className={style.main}>
        <CusAgGrid<AllPublishPathODTO>
          ref={gridRef}
          loading={loading}
          rowData={data?.records as AllPublishPathODTO[] | undefined}
          columnDefs={columnDefs}
          defaultColDef={defaultColDef}
          statusBar={statusBar}
        />
      </div>
    </div>
  )
}
